package com.ruoyi.ora.service.impl;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.AliMailUtil;
import com.ruoyi.common.utils.http.HttpRequest;
import com.ruoyi.common.utils.http.HttpRespons;
import com.ruoyi.ora.service.ICommonService;
import com.ruoyi.system.service.ISysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URLEncoder;

@Service
public class CommonServiceImpl implements ICommonService {

    private final static Logger logger = LoggerFactory.getLogger(CommonServiceImpl.class);

    @Autowired
    private ISysConfigService configService;
//    @Autowired
//    private RestTemplate restTemplate;

    @Override
    public boolean sendEmail(String[] receiveAccount, String subject, String content, String filePath) {
        String senderAccount = configService.selectConfigByKey("email_sender_account");
        String authCode = configService.selectConfigByKey("email_sender_authcode");;
        String nickName = configService.selectConfigByKey("platform_nick_name");;
        String mailReplay = configService.selectConfigByKey("email_replay_account");;
        String smtpHost = configService.selectConfigByKey("email_smtp_host");;
        String smtpPort = configService.selectConfigByKey("email_smtp_port");;
        return AliMailUtil.sendMail(senderAccount, authCode, nickName, receiveAccount, mailReplay, subject, content, filePath, smtpHost, smtpPort) > 0;
    }

    @Override
    public boolean sendSms(String phone, String content, String lang) {

        try {
            String url = configService.selectConfigByKey("sms_url_"+lang);
            String queryUrl = String.format(url, URLEncoder.encode(phone, Constants.UTF8), URLEncoder.encode(content, Constants.UTF8));

            HttpRequest httpRequest = new HttpRequest();
            HttpRespons hr = httpRequest.sendGet(queryUrl);

//            String result = restTemplate.getForObject(queryUrl , String.class);
            logger.info("sendSms request:{}，result:{}", queryUrl, hr.getContent().toString());
            return "0".equalsIgnoreCase(hr.getContent());
        }catch (Exception e){
            e.printStackTrace();
        }

        return false;
    }
}
